//
//  FeedbackViewController.swift
//  YLH
//
//  Created by qinjiangtao on 2024/1/12.
//

import UIKit
import HXPhotoPicker

class FeedbackViewController: QIBaseViewController {
    
    private var problemTextView = YYTextView()
    private var nameTextF = UITextField()
    private var phoneTextF = UITextField()
    private var catagoryArr = [String]()
    private var selectIndex = -1
    private var selectImages = [UIImage]()
    private var imageUrlArr = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "意见反馈"
        
        addUI()
        getData()
    }
    
    private func getData() {
        QINetworkManager.requestJson(urlStr: "/Advise/class", method: .get, parameters: [:]) { json in
             print(json)
            self.catagoryArr = json.rawValue as! [String]
            self.collectionView.reloadData()
        }
    }
   
    private func addUI() {
//        catagoryArr = ["更新慢", "不流畅", "耗流量", "书籍少", "更新慢", "不流畅", "耗流量", "书籍少"]
        
        let titleL = UILabel().then({
            $0.frame = CGRect(x: 20, y: NAV_HEIGHT + 10, width: SCREEN_WIDTH - 40, height: 20)
            $0.text = "反馈分类"
            $0.textColor = .black
            $0.font = SYSFONTBOLD(ofSize: 16)
        })
        view.addSubview(titleL)
        
        view.addSubview(collectionView)
        
        let titleL1 = UILabel().then({
            $0.frame = CGRect(x: 20, y: collectionView.bottom + 10, width: SCREEN_WIDTH - 40, height: 20)
            $0.text = "反馈问题"
            $0.textColor = .black
            $0.font = SYSFONTBOLD(ofSize: 16)
        })
        view.addSubview(titleL1)
        
        problemTextView = YYTextView().then({
            $0.frame = CGRect(x: 16, y: titleL1.bottom + 15, width: SCREEN_WIDTH - 30, height: 140)
            $0.backgroundColor = ColorEEEEEE
            $0.textContainerInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
            $0.placeholderText = "请简要说明你的问题"
            $0.placeholderTextColor = Color999999
            $0.font = SYSFONT(ofSize: 14)
            $0.addRoundedCorners(withRadius: 10)
        })
        view.addSubview(problemTextView)
        
        let titleL2 = UILabel().then({
            $0.frame = CGRect(x: 20, y: problemTextView.bottom + 10, width: SCREEN_WIDTH - 40, height: 20)
            $0.text = "问题图片"
            $0.textColor = .black
            $0.font = SYSFONTBOLD(ofSize: 16)
        })
        view.addSubview(titleL2)
        
        
        let manager = HXPhotoManager(type: .photo)
        manager?.configuration.type = .wxMoment
        manager?.configuration.photoMaxNum = 3
        manager?.configuration.requestImageAfterFinishingSelection = true
        
        let photoView = HXPhotoView(manager: manager)
        photoView?.frame = CGRect(x: 15, y: titleL2.bottom + 10, width: SCREEN_WIDTH - 30, height: 115)
        photoView?.lineCount = 3
        photoView?.spacing = 10
        photoView?.changeCompleteBlock = {allList, photos, videos, isOriginal in
            print(photos)
            if photos.count > 0 {
                for model in photos {
                    model.requestPreviewImage(with: CGSize(width: 10000, height: 10000)) { _, _ in
                        
                    } progressHandler: { _, _ in
                        
                    } success: { img, a, b in
                        self.selectImages.append(img ?? imageName(str: "noo"))
                    }
                }
            } else {
                
            }
        }
        view.addSubview(photoView!)
        
        
        let titleL3 = UILabel().then({
            $0.frame = CGRect(x: 20, y: photoView!.bottom + 10, width: SCREEN_WIDTH - 40, height: 20)
            $0.text = "联系姓名"
            $0.textColor = .black
            $0.font = SYSFONTBOLD(ofSize: 16)
        })
        view.addSubview(titleL3)
        
        let leftView = UIView()
        leftView.frame = CGRect(x: 0, y: 0, width: 15, height: 0)
        nameTextF = UITextField().then {
            $0.frame = CGRect(x: 16, y: titleL3.bottom + 10, width: SCREEN_WIDTH - 32, height: 42)
            $0.font = SYSFONT(ofSize: 13)
            $0.placeholder = "请输入姓名"
            $0.leftView = leftView
            $0.leftViewMode = .always
            $0.addRoundedCorners(withRadius: 5)
            $0.addBorder(withWidth: 1, borderColor: ColorEEEEEE)
        }
        view.addSubview(nameTextF)
        
        let titleL4 = UILabel().then({
            $0.frame = CGRect(x: 20, y: nameTextF.bottom + 10, width: SCREEN_WIDTH - 40, height: 20)
            $0.text = "联系电话"
            $0.textColor = .black
            $0.font = SYSFONTBOLD(ofSize: 16)
        })
        view.addSubview(titleL4)
        
        let leftView1 = UIView()
        leftView1.frame = CGRect(x: 0, y: 0, width: 15, height: 0)
        phoneTextF = UITextField().then {
            $0.frame = CGRect(x: 16, y: titleL4.bottom + 10, width: SCREEN_WIDTH - 32, height: 42)
            $0.font = SYSFONT(ofSize: 13)
            $0.placeholder = "请输入电话"
            $0.leftView = leftView1
            $0.keyboardType = .numberPad
            $0.leftViewMode = .always
            $0.addRoundedCorners(withRadius: 5)
            $0.addBorder(withWidth: 1, borderColor: ColorEEEEEE)
        }
        view.addSubview(phoneTextF)
        
        let submitBtn = UIButton().then {
            $0.frame = CGRect(x: 16, y: phoneTextF.bottom + 20, width: SCREEN_WIDTH - 32, height: 44)
            $0.backgroundColor = MainColor
            $0.titleLabel?.font = SYSFONT(ofSize: 14)
            $0.setTitle("提交", for: .normal)
            $0.setTitleColor(.white, for: .normal)
            $0.addRoundedCorners(withRadius: 22)
            $0.addTarget(self, action: #selector(updateImage), for: .touchUpInside)
        }
        view.addSubview(submitBtn)
        
    }
    
    @objc private func submitBtnClick() {
        let class_name = catagoryArr[selectIndex]
        let problemStr = problemTextView.text ?? ""
        let nameStr = nameTextF.text ?? ""
        let phoneStr = phoneTextF.text ?? ""
        let imageStr = imageUrlArr.joined(separator: ",")
        guard selectIndex > -1 else {
            ShowHUD(str: "请选择分类")
            return
        }
        guard nameStr.count > 0 else {
            ShowHUD(str: "请输入姓名")
            return
        }
        guard phoneStr.count > 0 else {
            ShowHUD(str: "请输入电话")
            return
        }
        let param = [
            "class_name": class_name,
            "content": problemStr,
            "images": imageStr,
            "mobile": phoneStr,
            "name": nameStr,
        ]
        print(param)
        QINetworkManager.requestJson(urlStr: "/Advise/add", parameters: param) { json in
            print(json)
            ShowHUD(str: "意见反馈成功!")
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    @objc private func updateImage() {
        
        imageUrlArr.removeAll()
        let group = DispatchGroup()
        let queue = DispatchQueue(label: "image", qos: .default)
        
        for image in selectImages {
            group.enter()
            QINetworkManager.uploadImage(urlStr: "", image: image) { json in
                let imgUrl = "\(json["url"] ?? "")"
                self.imageUrlArr.append(imgUrl)
                group.leave()
            }
        }
        group.notify(queue: queue) {
            print("全部上传完毕")
            print(self.imageUrlArr)
            DispatchQueue.main.async {
                self.submitBtnClick()
            }
        }
    }
    
    
    lazy var collectionView: UICollectionView = {
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.minimumLineSpacing = 10
        flowLayout.minimumInteritemSpacing = 10
        flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
        
        let collectionView = UICollectionView(frame: CGRect(x: 10, y: NAV_HEIGHT + 60, width: SCREEN_WIDTH - 20, height: 80), collectionViewLayout: flowLayout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = .white
        collectionView.register(FeedbackViewCell.classForCoder(), forCellWithReuseIdentifier: "FeedbackViewCell")
        collectionView.register(UICollectionReusableView.classForCoder(), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "headerView")
        
        return collectionView
    }()
    
}

extension FeedbackViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 73, height: 32)
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return catagoryArr.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "FeedbackViewCell", for: indexPath) as! FeedbackViewCell
        cell.titleStr = catagoryArr[indexPath.row]
        if selectIndex == indexPath.row {
            cell.titleL.backgroundColor = MainColor
            cell.titleL.textColor = .white
        } else {
            cell.titleL.backgroundColor = ColorEEEEEE
            cell.titleL.textColor = Color333333
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        selectIndex = indexPath.row
        collectionView.reloadData()
    }
}



class FeedbackViewCell: UICollectionViewCell {
    
    var titleL = UILabel()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .white
        addUI()
    }
    
    private func addUI() {
        titleL = UILabel().then({
            $0.frame = CGRect(x: 0, y: 0, width: self.width, height: self.height)
            $0.backgroundColor = ColorEEEEEE
            $0.textColor = .white
            $0.textAlignment = .center
            $0.font = SYSFONT(ofSize: 13)
            $0.addRoundedCorners(withRadius: self.height / 2)
        })
        self.addSubview(titleL)
    }
    
    var titleStr = "" {
        didSet {
            titleL.text = titleStr
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
